package com.huluobo.base.net

import android.util.Log
import com.blankj.utilcode.util.EncryptUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject

/**
 *  Created by LC on 2024/9/29.
 */
class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val builder = request.newBuilder()

        val body = chain.request().body
        val buffer = Buffer()
        body?.writeTo(buffer)
        val bodyString = buffer.toString()
        Log.i("TagA", "bodyString:$bodyString")
        buffer.close()

        val jsonStr = bodyString.substring(bodyString.indexOf("{"), bodyString.lastIndexOf("}")+1)
        Log.i("TagA", "jsonStr:$jsonStr")

        val sb = StringBuffer()
        val jsonObject = JSONObject(jsonStr)
        val keys = jsonObject.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            val value = jsonObject.getString(key)
            sb.append(value)
        }

        sb.append("tamboo")
        Log.i("TagA", "sb:${sb.toString()}")

        val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()

        jsonObject.put(Const.PARAM_SIGN, sign)
        Log.i("TagA", "sign:$sign")
        val requestBody = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), jsonObject.toString())
        builder.post(requestBody)
        request = builder.build()
        return chain.proceed(request)
    }
}